import {Component, OnInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from "../../../../widgets/one-operation/one-operation.component";
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {MonitorService} from "../monitor.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants, API} from "../../../../constants/constants";
import {TableUtil} from "../../../../util/table-util";

declare  var $;

@Component({
  selector: 'app-site-device-pollutant',
  templateUrl: './site-device-pollutant.component.html'
})
export class SiteDevicePollutantComponent implements OnInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  snCode: string;
  operaIdArr:Array<string> =[];
  table;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private monitorService: MonitorService,
    private dialogService: OneDialogService
  ) { }

  ngOnInit() {
    this.pushPage();
    if(!!this.route.snapshot.params["snCode"]){
      this.snCode = this.route.snapshot.params["snCode"];
      this.initOperationData();
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("运维管理", null);
    this.pageSubject.pushPage("设备管理", "分配权重", path);
  }

  /**
   * 刷新页面
   */
  reLoad(){
    this.table.bootstrapTable('refresh');
  }

  /**
   * 保存操作
   * 1.点击保存时，获取数据；
   * 2.移除修改行，点击事件；
   * 3.绑定所有行，点击事件；
   * 4.提交编辑后的数据；
   */
  savePollutant() {
    //获取数据
    let params = this.getEditRowData();
    if(!params){
      return;
    }
    this.dealClickEventAfterGetDat();
    //提交数据
    this.monitorService.siteMonitorSetAddOrEdit(params, this.snCode).subscribe(
      result => this.responseUtil.success(result, this.getOperationAddFormData),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 数据保存后，处理点击事件
   */
  dealClickEventAfterGetDat(){
    //提交成功,清楚data-edit
    this.table.removeData("edit");
    this.table.find(" .one-table-edit input").each(function (i, elem) {
      var text = $(elem).val();
      $(elem).parent().html(text);
    });
    //绑定点击事件
    this.table.find("tbody tr").removeData("edit").off("click").on("click", (e) => this.rowClick(e));
    //去掉新增行的input或触发刷新
    // this.reLoad();

  }

  goBack() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 删除操作
   * 1.未勾选数据时，模态框提示；
   * 2.勾选一条或多条进行删除
   */
  deletePollutant() {
    this.getSelectedCheckboxValue();
    if (this.operaIdArr.length != 1 || this.operaIdArr[0] == "") {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete,this.cancelDelOper);
    }
  }

  /**
   * 确认删除按钮
   * 1.单一删除；
   */
  private requestDelete = () => {
    //调用后端接口
    if (this.operaIdArr.length == 1 && this.operaIdArr[0] != "" ) {
      this.monitorService.siteMonitorSetDelete(this.operaIdArr[0]).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }
  }

  /**
   * 对删除结果进行处理
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.clearArrayData();
      this.reLoad();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
      this.clearArrayData();
    }
  }

  /**
   * 取消删除
   * 1.取消删除时，清空数组；
   */
  private cancelDelOper = () => {
    if (this.operaIdArr.length != 0) {
      this.clearArrayData();
    }
  }

  /**
   * 获取勾选复选框的值
   * 1.遍历勾选的复选框；
   * 2.把value值存入数组；
   */
  getSelectedCheckboxValue(){
    $(".table tr td:first-child input[type=checkbox]:checked").each(function(i,elem){
      this.operaIdArr.push($(elem).val());
    }.bind(this));
  }

  /**
   * 清空数组
   */
  private clearArrayData(){
    this.operaIdArr.splice(0,this.operaIdArr.length);
  }

  /**
   * 对添加修改结果进行处理
   * @param result
   */
  private getOperationAddFormData = (result: MsgResult) => {
    if (MsgConstants.MSG_CODE_OK == result.code) {
      this.dialogService.success(result.message);
      this.reLoad();
    } else {
      this.dialogService.error(result.message);
    }
  }

  /**
   * 处理编辑行数据
   * @returns {string}
   */
  private getEditRowData() {
    let datas: string = "";
    let isPass = true,errMsg="";
    this.table.find("tbody tr").each(function (i, n) {
      if ('1' != $(n).data('edit')) {
        return;
      }
      var data = new Array(8);

      $(n).find("td").each(function (i, m) {
        if(i == 1){
          //获取下拉框的值
          data[i] = $(m).find($(".pollutant")).val();
        }else{
          data[i] = $(m).find("input").val();
        }
      });

      if (!(/^[a-zA-Z0-9]+$/.test(data[1]))){
        isPass = false;
        errMsg = "项目代码必须是数字或字母!";
        return;
      }

      if (data[2] >= 1000000.0000 || -1000000.0000 >= data[2]){
        errMsg = "回归曲线斜率必须在[-1000000.0000,1000000.0000]区间内！";
        isPass = false;
        return;
      }
      if (data[3] >= 1000000.0000 || -1000000.0000 >= data[3]){
        errMsg = "y轴方向截距必须在[-1000000.0000,1000000.0000]区间内！";
        isPass = false;
        return;
      }
      if (data[4] >= 1000000.0000 || -1000000.0000 >= data[4]){
        errMsg = "相关系数必须在[-1000000.0000,1000000.0000]区间内！";
        isPass = false;
        return;
      }
      if (data[5] >= 1000000.0000 || -1000000.0000 >= data[5]){
        errMsg = "设备权重必须在[-1000000.0000,1000000.0000]区间内！";
        isPass = false;
        return;
      }
      if (data[6] >= 1000000.0000 || -1000000.0000 >= data[6]){
        errMsg = "标准权重必须在[-1000000.0000,1000000.0000]区间内！";
        isPass = false;
        return;
      }

      datas = "id=" + $.trim(data[0]) + "&itemCode=" +  $.trim(data[1]) + "&regrSlope=" +  $.trim(data[2]) + "&regrInter=" +  $.trim(data[3])
        + "&regrR2=" +  $.trim(data[4]) + "&deviceWeight=" +  $.trim(data[5]) + "&standStationWeight=" +  $.trim(data[6])
        + "&isUse=" +  $.trim(data[7]) ;
    });

    if(isPass){
      return datas;
    }
    this.dialogService.modalInfo(errMsg);
    return null;
  }

  rowClick(event) {
    let isEdit = this.table.data("edit");
    let tr = event.currentTarget;

    if ("1" != isEdit) {
      //添加行
      this.editRow(tr);
      this.table.data('edit', "1");
      this.table.find("tr").off("click");
    } else {
      //提示保存
      this.dialogService.infoWithCancelBtn("有数据未保存，是否先保存？", () => this.savePollutant())
    }
  }

  editRow(tr) {
    $(tr).find("td").each(function (i, n) {
      if ($(n).children().length == 0) {
        var content = $(n).html();
        $(n).addClass("one-table-edit").html('<input type="text">').find("input").val(content);
      }
    }).parent().data('edit', "1");
  }

  addPollutant() {
    let isEdit = this.table.data("edit");
    if ("1" != isEdit) {
      //添加行
      this.addRow();
      this.table.data('edit', "1");
    } else {
      //提示保存
      this.dialogService.infoWithCancelBtn("有数据未保存，是否先保存？", () => this.savePollutant());
    }
  }

  addRow() {
    let i=0;
    this.table.bootstrapTable('append', this.appendData());
    $("tbody tr:last-child", "#one_table_pollutant").find("td").each(function () {

      if ($(this).children().length == 0) {
        var content = $(this).html();
          i++;
        if (i == 1){
          $(this).addClass("one-table-edit").html(`<select class="multiselect form-control pollutant" id="">
          <option value="CO" selected >CO</option>
          <option value="SO2" >SO2</option>
          <option value="NO2" >NO2</option>
          <option value="O3" >O3</option>
          <option value="PM10" >PM10</option>
          <option value="PM25" >PM25</option>
          </select>`).find("input").val(content);
        }else{
          $(this).addClass("one-table-edit").html('<input type="text">').find("input").val(content);
        }
      }
    }).parent().data('edit', "1")
      .css("padding-top", "13px");
  }

  appendData() {
    let append = [{
      id : '',
      itemCode : '',
      regrSlope : '',
      regrInter : '',
      regrR2 : '',
      deviceWeight : '',
      standStationWeight: '',
      isUse : ''
    }];
    return append;
  }

  initOperationData() {
    this.table = this.tableUtil.load("one_table_pollutant",{
      columns: [
        {
          field: 'id',
          width: 20 ,
          title: '<input type="checkbox" />',
          formatter: function (value) {
            return '<input type= "checkbox" value="' + value + '">';
          }
        } ,{
          field: 'itemCode',
          title: '监测项目代码',
          align: "rig",
          halign: "center",
          width: 100,
          formatter: this.selectOperation
        },{
          field: 'regrSlope',
          title: '回归曲线斜率',
          align: "right",
          halign: "center",
          width: 100
        },{
          field: 'regrInter',
          title: '回归曲线y轴方向截距',
          align: "right",
          halign: "center",
          width: 100
        },{
          field: 'regrR2',
          title: '回归曲线相关系数',
          align: "right",
          halign: "center",
          width: 100
        },{
          field: 'deviceWeight',
          title: '设备权重',
          align: "right",
          halign: "center",
          width: 100
        },{
          field: 'standStationWeight',
          title: '标准站权重',
          align: "right",
          halign: "center",
          width: 100
        },{
          field: "isUse",
          title: "是否启用",
          width: 50,
          formatter: function (value) {
            if (value == "1") {
              return '<input type= "checkbox" checked value= 1>';
            }
            if (value != "1") {
              return '<input type= "checkbox" value= 0>';
            }
            return value;
          },
        }
      ],
      undefinedText: "",
      height: 711,
      toolbar: "#one_toolbar_pollutant",
      url: API.siteMonitorSetBySnCode,
      method: 'get',
      sortable:false,
      contentType: "application/x-www-form-urlencoded",
      //传递附加参数
      queryParams: (params) => {
        params.snCode = this.snCode;
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        this.responseUtil.preSuccess(result);
        return {data: result.data};
      },
      onClickCell: (field, value, row, element) => {

        if ("isUse" == field) {
          this.updateCheckValue(element);
        }
      },
      onLoadSuccess:()=>{
        this.table.removeData("edit");
        this.bindRowClick();
      }
    });
  }

  private selectOperation(value, row, index) {
    if (value == 'CO') {
      return `<select class="multiselect form-control pollutant" id="">
                      <option value="CO" selected >CO</option>
                      <option value="SO2" >SO2</option>
                      <option value="NO2" >NO2</option>
                      <option value="O3" >O3</option>
                      <option value="PM10" >PM10</option>
                      <option value="PM25" >PM25</option>
               </select>`;
    }
    if (value == 'SO2') {
      return `<select class="multiselect form-control pollutant" id="">
                <option value="CO" >CO</option>
                <option value="SO2" selected >SO2</option>
                <option value="NO2" >NO2</option>
                <option value="O3" >O3</option>
                <option value="PM10" >PM10</option>
                <option value="PM25" >PM25</option>
              </select>`;
    }
    if (value == 'NO2') {
      return `<select class="multiselect form-control pollutant" id="">
                <option value="CO" >CO</option>
                <option value="SO2" >SO2</option>
                <option value="NO2" selected >NO2</option>
                <option value="O3" >O3</option>
                <option value="PM10" >PM10</option>
                <option value="PM25" >PM25</option>
              </select>`;
    }
    if (value == 'O3') {
      return `<select class="multiselect form-control pollutant" id="">
                <option value="CO" >CO</option>
                <option value="SO2" >SO2</option>
                <option value="NO2" >NO2</option>
                <option value="O3" selected >O3</option>
                <option value="PM10" >PM10</option>
                <option value="PM25" >PM25</option>
              </select>`;
    }
    if (value == 'PM10') {
      return `<select class="multiselect form-control pollutant" id="">
                <option value="CO" >CO</option>
                <option value="SO2" >SO2</option>
                <option value="NO2" >NO2</option>
                <option value="O3" >O3</option>
                <option value="PM10" selected >PM10</option>
                <option value="PM25" >PM25</option>
              </select>`;
    }
    if (value == 'PM25') {
      return `<select class="multiselect form-control pollutant" id="">
                <option value="CO" >CO</option>
                <option value="SO2" >SO2</option>
                <option value="NO2" >NO2</option>
                <option value="O3" >O3</option>
                <option value="PM10" >PM10</option>
                <option value="PM25" selected >PM25</option>
              </select>`;
    }
  }

  private bindRowClick(){
    this.table.find("tbody tr").off("click").on("click", (e) => this.rowClick(e));
  }

  /**
   *复选框勾选赋值处理
   * @param element
   */
  updateCheckValue(element) {
    $(element.children()[0]).attr('value', element.children()[0].checked ? 1 : 0);
    element.attr('value', element.children()[0].checked ? 1 : 0);
  }


}
